/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */
package org.jaxson.struts.charts.pie;

import java.awt.Color;
import java.util.Iterator;
import java.util.Map;

import org.jaxson.struts.charts.AbstractChartRenderer;
import org.jaxson.struts.charts.ChartFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.PieDataset;

/**
 * Renderer for a Pie Chart.
 * 
 * @author Joe Maisel
 *
 */
public class PieChartRenderer extends AbstractChartRenderer
{
	/**
	 * @see org.jaxson.struts.charts.AbstractChartRenderer#render(Dataset, ChartFormat)
	 */
	@Override
	public JFreeChart render(Dataset dataset, ChartFormat format)
	{
		JFreeChart result = null;
		PieDataset ds = (PieDataset)dataset;
		PieChartFormat f = (PieChartFormat)format;
		
		if( f.is3D() )
			result = ChartFactory.createPieChart3D( null, ds, f.isShowLegend(), f.isShowTooltips(), f.getLocale() );
		else
			result = ChartFactory.createPieChart( null, ds, f.isShowLegend(), f.isShowTooltips(), f.getLocale() );
		
		if( f.getTitle() != null && f.isShowTitle() )
		{
			TextTitle title = new TextTitle( f.getTitle() );
			title.setExpandToFitSpace( f.isExpandTitle() );
			result.setTitle( title );
		}
		
		PiePlot plot = (PiePlot) result.getPlot();
		plot.setToolTipGenerator( f.getToolTipGenerator() );
		plot.setURLGenerator( f.getUrlGenerator() );
		
		if( f.getLabelGenerator() != null )
		{
			plot.setLabelGenerator( f.getLabelGenerator() );
		}

		if( f.getLabelFont() != null )
		{
			plot.setLabelFont( f.getLabelFont() );
		}

		if( f.getBackgroundColor() != null )
		{
			plot.setBackgroundPaint( f.getBackgroundColor() );
		}
		
		Map<String, Color> paint = f.getPaint();
		Iterator<String> keys = paint.keySet().iterator();
		while( keys.hasNext() )
		{
			String key = keys.next();
			Color color = paint.get( key );
			plot.setSectionPaint( key, color );
		}
		
		return result;
	}

}
